<?php
namespace Reseller\Model;

/**
 * 订单提交
 */
class OrderSubmitModel extends BaseModel
{
    public $adult_num;
    public $child_num;
    public $total_num;
    public $day; //出团时间
    public $travel_days; //行程天数
    public $line;
    public $total_money = 0;
    /**
     * 游客信息提交处理
     * @param array $p post到的参数
     * @param array    结果数组
     */
    public function submitTouristInfo($p)
    {
        if (empty($p) || !is_array($p)) {
            return ['status' => -2, 'msg' => '非法参数'];
        }
        $p                 = $this->arrayRemoveEmpty($p);
        $this->line        = M('public_line')->where(['line_id' => $p['line_id']])->find();
        $this->reseller_id = session('reseller_user.pid') ? session('reseller_user.pid') : session('reseller_user.reseller_id');
        $this->total_num   = $p['adult_num'] + $p['child_num'];
        $this->adult_num   = $p['adult_num'] ? $p['adult_num'] : 0;
        $this->child_num   = $p['child_num'] ? $p['child_num'] : 0;
        $this->day         = $p['day'];
        $this->travel_days = $this->line['travel_days'];
        M()->startTrans();
        //是否特殊日期
        $price = M('operator_special_price')
            ->field('adult_price,child_price')
            ->where(['line_id' => $this->line['line_id'], 'day' => str_replace('-', '', $this->day)])
            ->find();
        if (empty($price)) {
            //销售价格
            $price = M('line_reseller_price')
                ->field('adult_price,child_price')
                ->where([
                    'line_id' => $this->line['line_id'],
                    [
                        'rp_type' => 0,
                        '_logic'  => 'or',
                        [
                            'reseller_id' => $this->reseller_id,
                            'rp_type'     => session('reseller_user.shop_or_reseller'),
                        ],
                    ],
                ])
                ->find();
        }

        $this->total_money += $this->adult_num * $price['adult_price'] + $this->child_num * $price['child_price'];
        // dump('基础价格：'.$this->total_money);
        //优惠信息
        if ($p['discounts'] && ($p['adult_num'] + $p['child_num'] >= $this->line['discounts_condition'])) {
            $discounts = $this->line['discounts'];
        }
        // dump('优惠信息'.$this->total_money);
        //签证信息
        if ($p['visa'] > 0) {
            $visa_price = $this->line['visa_price'];
            $this->total_money += $this->adult_num * $visa_price + $this->child_num * $visa_price;
        }
        // dump('签证信息'.$this->total_money);
        //下单
        $this->order_id = $this->addOrder($discounts, $visa_price);
        //生成团号
        $this->group_id = $this->addGroup($order_id);

        //景区处理
        $this->scenic();
        //交通方式
        if (!empty($p['traffic'])) {
            $this->traffic();
        }

        //酒店升级服务
        if (!empty($p['up_hotel'])) {
            $up_hotel = $this->upHotel($p['up_hotel']);
        }
        // dump('酒店升级服务'.$this->total_money);
        //标准酒店补房差
        if (!empty($p['hotel'])) {
            $hotel = $this->hotel($p['hotel'], $p['new_hotel'], $this->line['add_room_price']);
        }
        // dump(M('order_unit_detail')->where(['order_id'=>$this->order_id,'source_type'=>2])->select());die;
        // dump('标准酒店补房差'.$this->total_money);
        //交通方式升级
        if (!empty($p['up_traffic'])) {
            $up_traffic = $this->upTraffic($p['up_traffic'], $p['back_price_id'], $p['go_price_id']);
        }
        // dump('交通方式升级'.$this->total_money);
        //保险信息
        if ($p['insure']) {
            $this->insure($p['insure']);
        }
        // dump('保险信息'.$this->total_money);
        //附加产品
        if (!empty($p['product'])) {
            $this->addProduct($p['product']);
        }
        // dump('附加产品'.$this->total_money);die;
        //添加游客信息
        $this->tourist($p['tourist']);

        //游客信息
        $tourists = M('public_tourists')
        // ->field('tourists_id,is_contact')
        ->where(['order_id' => $this->order_id])
            ->select();

        //查找联系人
        foreach ($tourists as $v) {
            if ($v['is_contact'] == 1) {
                $contenct_id = $v['tourists_id'];
                break;
            }
        }
        $tourists_ids = $this->levelDown($tourists);
        $data         = [
            'group_id'     => $this->group_id,
            'tourists_ids' => $tourists_ids,
            'total_money'  => $this->total_money,
            'need_pay'     => $this->total_money - $discounts,
            'end_need_pay' => $this->total_money - $discounts,
            'close_money'  => $this->total_money - $discounts,
            'contact_id'   => $contenct_id,
            'leave_num'    => M('day_seat')->where(['day' => $this->day, 'line_id' => $this->line['line_id']])->getField('surplus_tourist'),
        ];
        $res = M('line_orders')->where(['order_id' => $this->order_id])->save($data);
        A('Operator/Closing')->supplierClosing($order_id);
        if ($res === false) {
            M()->rollback();
            die(json_encode(['status' => -11, 'msg' => '修改订单错误']));
        }
        M()->commit();
        return ['status' => 1, 'msg' => '下单成功', 'order_id' => $this->order_id];
    }

    //标准交通
    private function traffic()
    {
        $m        = M('day_traffice');
        $m_detail = M('order_unit_detail');
        $insert   = [];
        $traffic  = I('traffic');

        $info['go'] = M('public_single_traffic_price')
            ->field('traffic_priceId,adult_actual_cost,child_actual_cost,supplier_id')
            ->where(['traffic_priceId' => $this->line['go_price_id']])
            ->find();

        $info['back'] = M('public_single_traffic_price')
            ->field('traffic_priceId,adult_actual_cost,child_actual_cost,supplier_id')
            ->where(['traffic_priceId' => $this->line['back_price_id']])
            ->find();
        foreach ($info as $k => $v) {
            $time                 = ($k == 'go' ? $this->day : $this->dateTime($this->line['travel_days']));
            $where                = ['day' => $time, 'traffic_priceId' => $v['traffic_priceId']];
            $traffic[$k]['adult'] = $traffic[$k]['adult'] ? $traffic[$k]['adult'] : 0;
            $traffic[$k]['child'] = $traffic[$k]['child'] ? $traffic[$k]['child'] : 0;
            $total_go             = array_sum($traffic[$k]);
            if ($total_go > 0) {
                $number = $m->where($where)->getField('surplus_seat');
                $res    = $m
                    ->where($where)
                    ->setDec('surplus_seat', $traffic[$k]['adult'] + $traffic[$k]['child']);
                $insert[] = [
                    'order_id'         => $this->order_id,
                    'source_type'      => 1,
                    'source_id'        => $v['traffic_priceId'],
                    'adult_count'      => $traffic[$k]['adult'],
                    'child_count'      => $traffic[$k]['child'],
                    'unit_cost'        => $v['adult_actual_cost'] * $traffic[$k]['adult'] + $v['child_actual_cost'] * $traffic[$k]['child'],
                    'unit_supplier_id' => $v['supplier_id'],
                    'status'           => 0,
                    'use_date'         => $time,
                    'group_id'         => $this->group_id,
                    'is_compose'       => ($k == 'go' ? $this->line['go_traffic_custom'] : $this->line['back_traffic_custom']),
                    'adult_price'      => $v['adult_actual_cost'] ? $v['adult_actual_cost'] : 0,
                    'child_price'      => $v['child_actual_cost'] ? $v['child_actual_cost'] : 0,
                    'traffic_go_back'  => ($k == 'go' ? 1 : 2),
                ];
                if ($res === false || $number < $total_go) {
                    M()->rollback();
                    die(json_encode(['status' => -7.5, 'msg' => '标准交通余位不足']));
                }
            }
        }
        $res1 = $m_detail->addAll($insert);
        if ($res1 === false) {
            M()->rollback();
            die(json_encode(['status' => -7.6, 'msg' => '标准交通信息写入失败']));
        }
    }

    /**
     * 景区
     */
    private function scenic()
    {
        $info = M('public_trip')
            ->field('scenic_spot,current_day')
            ->where([
                'line_id' => $this->line['line_id'],
                '_string' => 'scenic_spot is not null',
            ])
            ->select();

        if (empty($info)) {
            return TURE;
        }

        $scenic = M('public_single_scenic_price')
            ->where(['scenic_priceId' => ['in', implode(',', array_map('array_shift', $info))]])
            ->select();
        $scenic = $this->changeIndex($scenic);
        $data   = [];
        foreach ($info as $v) {
            $scenic_spot = explode(',', $v['scenic_spot']);
            foreach ($scenic_spot as $vv) {
                if ($vv && isset($scenic[$vv])) {
                    $data[] = [
                        'order_id'         => $this->order_id,
                        'source_type'      => 3,
                        'source_id'        => $scenic[$vv]['scenic_priceId'],
                        'adult_count'      => $this->adult_num,
                        'child_count'      => $this->child_num,
                        'unit_cost'        => $this->adult_num * $scenic[$vv]['adult_actual_cost'] + $this->child_num * $scenic[$vv]['child_actual_cost'],
                        'unit_supplier_id' => $scenic[$vv]['supplier_id'],
                        'status'           => 0,
                        'use_date'         => $this->dateTime($v['current_day']),
                        'group_id'         => $this->group_id,
                        'is_compose'       => $this->line['scenic_custom'],
                        'adult_price'      => $scenic[$vv]['adult_actual_cost'] ? $scenic[$vv]['adult_actual_cost'] : 0,
                        'child_price'      => $scenic[$vv]['child_actual_cost'] ? $scenic[$vv]['child_actual_cost'] : 0,
                    ];
                }
            }
        }
        $res = M('order_unit_detail')->addAll($data);
        if ($res === false) {
            M()->rollback();
            die(json_encode(['status' => -20, 'msg' => '景区数据插入失败']));
        }
    }

    /**
     * 添加订单
     * @param [float] $discounts  [优惠价格]
     * @param [float] $visa_price [签证价格]
     */
    private function addOrder($discounts = 0, $visa_price = 0)
    {
        //下单信息
        $data = [
            'order_num'               => implode('', explode('.', microtime(true))),
            'line_id'                 => $this->line['line_id'],
            'out_time'                => strtotime($this->day),
            'create_time'             => time(),
            'adult_num'               => $this->adult_num,
            'child_num'               => $this->child_num,
            'oldMan_num'              => 0,
            'preferential'            => $discounts ? $discounts : 0,
            'order_remarks'           => I('order_remarks'),
            'channel_reseller_id'     => $this->reseller_id,
            'sales_id'                => session('reseller_user.reseller_id'),
            'manager_id'              => $this->reseller_id,
            'total_num'               => $this->total_num,
            'order_type'              => session('reseller_user.shop_or_reseller'),
            'room_priceId'            => $this->line['room_price_id'],
            'scenic_priceId'          => $this->line['scenic_price_id'],
            'go_traffic_priceId'      => $this->line['go_price_id'],
            'back_traffic_priceId'    => $this->line['back_price_id'],
            'origin_line_supplier_id' => $this->line['supplier_id'],
            'visa_price'              => $visa_price ? $visa_price : 0,
            'operator_id'             => session('reseller_user.operator_id'),
            // 'insure_priceId' => $insure['insure_price_id'] ?  $insure['insure_price_id']: 0,
            // 'Insurancefee' => $insure['now_adult_price'] * $this->adult_num + $insure['now_child_price'] * $this->child_num
        ];
        $order_id = M('line_orders')->data($data)->add();
        // echo M()->_SQL();die;
        if ($order_id === false) {
            M()->rollback();
            die(json_encode(['status' => -3, 'msg' => '生成订单失败']));
        }
        return $order_id;
    }

    /**
     * 添加团号
     */
    private function addGroup()
    {
        $m     = M('public_group');
        $group = $m
            ->field('group_id,received_num')
            ->where(['out_time' => strtotime($this->day), 'line_id' => $this->line['line_id']])
            ->find();
        if ($group) {
            $group_id = $group['group_id'];
            $res      = $m->where(['group_id' => $group['group_id']])->setInc('received_num', $this->total_num);

            if ($group['received_num'] + $this->total_num > $this->line['guests_num']) {
                M()->rollback();
                die(json_encode(['status' => -4, 'msg' => '该团余位不足']));
            }

        } else {
            $data = [
                'group_num'      => $this->line['group_num'],
                'line_name'      => $this->line['line_name'],
                'group_time'     => 0,
                'out_time'       => strtotime($this->day),
                'start_site'     => M('areas')->where(['areaId' => $this->line['origin_id']])->getField('areaName'),
                'day_num'        => $this->line['travel_days'],
                'received_num'   => $this->total_num,
                'expect_num'     => $this->line['guests_num'],
                //'admin1_id'      => session('reseller_user.reseller_id'),
                'admin1_id'      => 0,
                'group_type'     => $this->line['platform'],
                'closing_status' => -1,
                'admin2_id'      => 0,
                'closing_time'   => 0,
                'line_id'        => $this->line['line_id'],
                'channel'        => 2,
                'shop_id'        => $this->reseller_id,
            ];
            $group_id = $m->add($data);
        }
        $res1 = M('day_seat')
            ->where(['day' => $this->day, 'line_id' => $this->line['line_id']])
            ->setDec('surplus_tourist', $this->total_num);

        if ($res === false || $res1 === false) {
            M()->rollback();
            die(json_encode(['status' => -4, 'msg' => '团号生成失败']));
        }
        return $group_id;
    }

    /**
     * 保险信息
     * @param  [int] $insure_id [保险id]
     */
    private function insure($insure_id)
    {
        $result = M('line_upgrade_insure as i')
            ->field('i.*, p.supplier_id,p.adult_actual_cost,p.child_actual_cost')
            ->join('LEFT JOIN __PUBLIC_SINGLE_INSURE_PRICE__ as p on i.insure_price_id = p.insure_priceId')
            ->where(['up_insure_id' => $insure_id])
            ->find();

        $data = [
            'order_id'            => $this->order_id,
            'source_type'         => 4,
            'source_id'           => $result['insure_price_id'] ? $result['insure_price_id'] : 0,
            'adult_count'         => $this->adult_num,
            'child_count'         => $this->child_num,
            'unit_cost'           => $result['child_actual_cost'] * $this->child_num + $result['adult_actual_cost'] * $this->adult_num,
            'unit_supplier_id'    => $result['supplier_id'] ? $result['supplier_id'] : 0,
            'status'              => 0,
            'use_date'            => $this->day,
            'group_id'            => $this->group_id,
            'is_compose'          => $this->line['insure_custom'],
            'adult_price'         => $result['adult_actual_cost'] ? $result['adult_actual_cost'] : 0,
            'child_price'         => $result['child_actual_cost'] ? $result['child_actual_cost'] : 0,
            'upgrade_adult_price' => $result['origin_adult_price'] ? $result['origin_adult_price'] : 0,
            'upgrade_child_price' => $result['origin_child_price'] ? $result['origin_child_price'] : 0,

        ];
        $res = M('order_unit_detail')->data($data)->add();
        if ($res === false) {
            M()->rollback();
            die(json_encode(['status' => -5, 'msg' => '保险信息写入失败']));
        }
        $this->total_money += $result['now_child_price'] * $this->child_num + $result['now_adult_price'] * $this->adult_num;
        // echo (__FUNCTION__ . ':' .$this->total_money);
    }

    /**
     * 标准酒店补房差
     * @param  [array] $hotel          [标准酒店id数组]
     * @param  [array] $new_hotel      [新增房间数组]
     * @param  [float] $add_room_price [补房差]
     */
    private function hotel($hotel, $new_hotel, $add_room_price)
    {

        $arr      = [];
        $temp     = [];
        $new_temp = [];
        //标准入住酒店房间号
        foreach ($hotel as $k => $v) {
            $temp[] = implode(',', array_keys($v));
        }
        $origin_add_room_price = M('public_line')
            ->where(['line_id' => $this->line['origin_line_id']])
            ->getField('add_room_price');
        $origin_add_room_price = $origin_add_room_price ? $origin_add_room_price : 0;

        $room = M('public_single_room_price')
            ->field('room_priceId,user_count,supplier_id,adult_actual_cost,child_actual_cost')
            ->where(['room_priceId' => ['in', implode(',', $temp)]])
            ->select();
        $room = $this->changeIndex($room);

        //统计每个房型的补房差人数
        //$k是行程第几天
        foreach ($new_hotel as $k => $v) {
            //$kk 是 room_priceId
            foreach ($v as $kk => $vv) {
                //$kkk 添加的房间 $vvv 添加房间的入住人数
                foreach ($vv as $kkk => $vvv) {
                    $new_hotel[$k][$kk]['room_count'] += 1;
                    $new_hotel[$k][$kk]['add_room_price'] += ($room[$kk]['user_count'] - $vvv) * $add_room_price;
                    $new_hotel[$k][$kk]['room_diff_cost'] += ($room[$kk]['user_count'] - $vvv) * $origin_add_room_price;
                    unset($new_hotel[$k][$kk][$kkk]);
                }
            }
        }
        $m        = M('day_hotel');
        $m_detail = M('order_unit_detail');
        $insert   = [];
        foreach ($hotel as $k => $v) {
            //普通房间供应商价格
            foreach ($v as $kk => $vv) {
                $hotel[$k][$kk] = [];
                //房间总数
                $hotel[$k][$kk]['room_count'] = $vv + ($new_hotel[$k][$kk] ? $new_hotel[$k][$kk]['room_count'] : 0);
                //房间总价格
                $hotel[$k][$kk]['unit_cost'] = $room[$kk]['adult_actual_cost'] * $hotel[$k][$kk]['room_count'];
                //补房差
                $hotel[$k][$kk]['add_room_price'] = $new_hotel[$k][$kk] ? $new_hotel[$k][$kk]['add_room_price'] : 0;
                $hotel[$k][$kk]['room_diff_cost'] = $new_hotel[$k][$kk] ? $new_hotel[$k][$kk]['room_diff_cost'] : 0;
            }

            $day = $this->dateTime($k);
            foreach ($hotel[$k] as $kk => $vv) {
                $hotel[$k][$kk]['supplier_id'] = $room[$kk]['supplier_id'];
                $this->total_money += $vv['add_room_price'];
                $where  = ['day' => $this->dateTime($k), 'room_priceId' => $kk];
                $number = $m->where($where)->getField('surplus_room');
                $res    = $m
                    ->where($where)
                    ->setDec('surplus_room', $vv['room_count']);
                $insert[] = [
                    'order_id'         => $this->order_id,
                    'source_type'      => 2,
                    'source_id'        => $kk,
                    'unit_cost'        => $vv['unit_cost'],
                    'unit_supplier_id' => $room[$kk]['supplier_id'],
                    'status'           => 0,
                    'use_date'         => $day,
                    'group_id'         => $this->group_id,
                    'is_compose'       => $this->line['room_custom'],
                    'room_count'       => $vv['room_count'],
                    'room_diff'        => $vv['add_room_price'],
                    'room_diff_cost'   => $vv['room_diff_cost'],
                    'adult_price'      => $room[$kk]['adult_actual_cost'] ? $room[$kk]['adult_actual_cost'] : 0,
                    'child_price'      => $room[$kk]['child_actual_cost'] ? $room[$kk]['child_actual_cost'] : 0,
                ];
                if ($res === false || $number < $vv['room_count']) {
                    M()->rollback();
                    die(json_encode(['status' => -6, 'msg' => '写入标准房间信息失败']));
                }
            }
        }
        $res1 = $m_detail->addAll($insert);
         // dump(M('order_unit_detail')->where(['order_id'=>$this->order_id,'source_type'=>2])->select());
        if ($res1 === false) {
            M()->rollback();
            die(json_encode(['status' => -6.1, 'msg' => '写入标准房间信息失败']));
        }
        // echo (__FUNCTION__ . ':' .$this->total_money);
    }

    /**
     * 附加产品
     * @param [array] $array [查询条件]
     */
    private function addProduct($array)
    {
        $product = M('line_additional_product')
            ->where(['product_id' => implode($array)])
            ->select();
        $insert = [];
        foreach ($product as $k => $v) {
            $this->total_money += $v['product_price'] * $this->total_num;
            $temp[] = [
                'order_id'     => $this->order_id,
                'product_name' => $v['product_name'],
                'origin_money' => $v['origin_product_price'],
                'now_money'    => $v['product_price'],
                'product_num'  => $this->total_num,
                'supplier_id'  => $v['supplier_id'],
                'operator_id'  => $v['operator_id'],
                'product_id'   => $v['product_id'],
                'group_id'     => $this->group_id,
            ];
        }
        $res = M('order_addition')->addAll($temp);
        if ($res === false) {
            M()->rollback();
            die(json_encode(['status' => -6, 'msg' => '附加产品信息写入失败']));
        }
        // echo (__FUNCTION__ . ':' .$this->total_money);
    }

    /**
     * 交通方式升级
     * @param  [type] &$traffic         [description]
     * @param  [int]  $go_price_id      [description]
     * @param  [int]  $back_price_id    [description]
     */
    private function upTraffic(&$traffic, $go_price_id, $back_price_id)
    {
        $arr = [];
        //来的升级交通方式
        if (!empty($traffic['go'])) {
            $this->dayTraffice($traffic['go'], 'go', $arr);
        }

        //回的升级交通方式
        if (!empty($traffic['back'])) {
            $this->dayTraffice($traffic['back'], 'back', $arr);
        }
        // echo (__FUNCTION__ . ':' .$this->total_money);
    }

    /**
     * 交通处理函数
     * @param  [type]   $traffic [description]
     * @param  [string] $key     ['back'回的交通方式， 'go'去的交通方式]
     * @param  [type]   &$arr    [description]
     */
    private function dayTraffice($traffic, $key, &$arr)
    {

        $m        = M('day_traffice');
        $m_detail = M('order_unit_detail');
        $insert   = [];
        $go       = M('line_upgrade_traffic as l')
            ->field('l.*, p.supplier_id,child_actual_cost,adult_actual_cost')
            ->join('LEFT JOIN __PUBLIC_SINGLE_TRAFFIC_PRICE__ as p on l.traffic_price_id = p.traffic_priceId')
            ->where(['up_traffic_id' => ['in', implode(',', array_keys($traffic))]])
            ->select();
        $go = $this->changeIndex($go);
        if ($key == 'go') {
            $arr[$key]['day'] = $this->day;
            $day              = $this->day;
            $flag             = 1;
        } else {
            $arr[$key]['day'] = $this->dateTime($this->travel_days);
            $day              = $arr[$key]['day'];
            $flag             = 2;
        }

        foreach ($traffic as $k => $v) {
            $arr[$key][$k] = array_merge($v, $go[$k]);
            $where         = ['day' => $day, 'traffic_priceId' => $go[$k]['traffic_price_id']];
            $number        = $m->where($where)->getField('surplus_seat');
            $v['adult']    = $v['adult'] ? $v['adult'] : 0;
            $v['child']    = $v['child'] ? $v['child'] : 0;
            $res           = $m
                ->where($where)
                ->setDec('surplus_seat', $v['adult'] + $v['child']);
            $money    = $go[$k]['now_adult_price'] * $v['adult'] + $go[$k]['now_child_price'] * $v['child'];
            $insert[] = [
                'order_id'            => $this->order_id,
                'source_type'         => 1,
                'source_id'           => $go[$k]['traffic_price_id'],
                'adult_count'         => $v['adult'],
                'child_count'         => $v['child'],
                'unit_cost'           => $go[$k]['adult_actual_cost'] * $v['adult'] + $go[$k]['child_actual_cost'] * $v['child'],
                'unit_supplier_id'    => $go[$k]['supplier_id'],
                'status'              => 0,
                'use_date'            => $day,
                'group_id'            => $this->group_id,
                // 'is_compose'          => $this->line['traffic_custom'],
                'now_cost'            => $money,
                'is_upgrade'          => 1,
                'is_compose'          => ($key == 'go' ? $this->line['go_traffic_custom'] : $this->line['back_traffic_custom']),
                'adult_price'         => $go[$k]['adult_actual_cost'] ? $go[$k]['adult_actual_cost'] : 0,
                'child_price'         => $go[$k]['child_actual_cost'] ? $go[$k]['child_actual_cost'] : 0,
                'upgrade_adult_price' => $go[$k]['origin_adult_price'] ? $go[$k]['origin_adult_price'] : 0,
                'upgrade_child_price' => $go[$k]['origin_child_price'] ? $go[$k]['origin_child_price'] : 0,
                'traffic_go_back'     => $flag,
            ];
            if ($res === false || $number < $this->total_num) {
                M()->rollback();
                die(json_encode(['status' => -7, 'msg' => '交通升级信息余位不足']));
            }
            $this->total_money += $money;
        }
        $res1 = $m_detail->addAll($insert);
        // echo M()->_sql();exit;
        if ($res1 === false) {
            M()->rollback();
            die(json_encode(['status' => -7.1, 'msg' => '交通升级信息写入失败']));
        }

    }

    /**
     * 酒店升级
     * @param  [array] $up_hotel [description]
     */
    private function upHotel($upHotel)
    {
        $arr      = [];
        $temp     = [];
        $insert   = [];
        $m_detail = M('order_unit_detail');
        $m        = M('day_hotel');
        foreach ($upHotel as $k => $v) {
            $temp[] = implode(',', array_keys($v));
        }
        $hotel = M('line_upgrade_hotel as h')
            ->field('h.*, p.supplier_id,child_actual_cost,adult_actual_cost')
            ->join('LEFT JOIN __PUBLIC_SINGLE_ROOM_PRICE__ as p on h.room_price_id = p.room_priceId')
            ->where(['up_hotel_id' => ['in', implode(',', $temp)]])
            ->select();
        $hotel = $this->changeIndex($hotel);
        reset($upHotel);
        foreach ($upHotel as $k => $v) {
            $upHotel[$k]['day'] = $this->dateTime($k);
            //$vv表示使用的房间的数量
            foreach ($v as $kk => $vv) {
                $upHotel[$k][$kk]               = $hotel[$kk];
                $upHotel[$k][$kk]['room_count'] = $vv;
                $where                          = ['day' => $upHotel[$k]['day'], 'room_priceId' => $hotel[$kk]['room_price_id']];
                $number                         = $m->where($where)->getField('surplus_room');
                $res                            = $m
                    ->where($where)
                    ->setDec('surplus_room', $vv);
                $insert[] = [
                    'order_id'               => $this->order_id,
                    'source_type'            => 2,
                    'source_id'              => $hotel[$kk]['room_price_id'],
                    'unit_cost'              => $vv * $hotel[$kk]['adult_actual_cost'],
                    'unit_supplier_id'       => $hotel[$kk]['supplier_id'],
                    'status'                 => 0,
                    'use_date'               => $upHotel[$k]['day'],
                    'group_id'               => $this->group_id,
                    'room_count'             => $vv,
                    'room_to_operator_price' => $this->line['origin_line_id'] > 0 ? $hotel[$kk]['to_operator_price'] * $vv : 0,
                    'is_compose'             => $this->line['room_custom'],
                    'now_cost'               => $vv * $hotel[$kk]['now_adult_price'],
                    'is_upgrade'             => 1,
                    'adult_price'            => $hotel[$kk]['adult_actual_cost'] ? $hotel[$kk]['adult_actual_cost'] : 0,
                    'child_price'            => $hotel[$kk]['child_actual_cost'] ? $hotel[$kk]['child_actual_cost'] : 0,
                ];
                $this->total_money += $vv * $hotel[$kk]['now_adult_price'];
                // if(session('reseller_user.reseller_id') == 7){
                //     dump($res);
                //     dump($number);
                //     dump($vv);
                //     dump($number < $vv);
                //     die;
                // }
                if ($res === false || $number < $vv) {
                    M()->rollback();
                    die(json_encode(['status' => -9, 'msg' => '升级酒店余位不足']));
                }
            }
        }
        $res1 = $m_detail->addAll($insert);
        if ($res1 === false) {
            M()->rollback();
            die(json_encode(['status' => -9, 'msg' => '升级酒店订单信息新增失败']));
        }
        // echo (__FUNCTION__ . ':' .$this->total_money);
    }

    private function tourist($info)
    {
        $contenct_index = $info['contenct'];
        $insert_v       = [];
        $insert_t       = [];
        unset($info['contenct']);
        $m_t = M('public_tourists');
        $m_v = M('public_visitor_info');
        foreach ($info as $k => $v) {
            //是否在游客信息表里有信息
            $phone = $m_v->where(['visitor_phone' => $v['tourists_phone']])->getField('tourists_id');
            //没有记录
            if (!$phone) {
                //填写了手机
                if ($v['tourists_phone']) {
                    $insert_v[] = [
                        'visitor_name'    => $v['name'] ? $v['name'] : '',
                        'visitor_sex'     => $v['sex'],
                        'visitor_phone'   => $v['visitor_phone'] ? $v['visitor_phone'] : '',
                        'documents_num'   => $v['documents_num'] ? $v['documents_num'] : '',
                        'source_type'     => 2,
                        'consume_num'     => 1,
                        'visitor_status'  => 1,
                        'sales_id'        => session('reseller_user.reseller_id'),
                        'entry_id'        => session('reseller_user.reseller_id'),
                        'entry_time'      => time(),
                        'reseller_id'     => $this->reseller_id,
                        'order_id'        => $this->order_id,
                        'visitor_address' => $v['tourists_address'],
                    ];
                }
                //有记录 表示有手机
            } else {
                $res = $m_v->where(['visitor_phone' => $v['tourists_phone']])->setInc('consume_num');
                if ($res === false) {
                    M()->rollback();
                    die(json_encode(['status' => 10, 'msg' => '游客信息写入失败']));
                }
            }
            $insert_t[] = [
                'tourists_name'    => $v['name'] ? $v['name'] : '', //
                'tourists_sex'     => $v['sex'],
                'documents_type'   => $v['documents_type'],
                'documents_num'    => $v['documents_num'] ? $v['documents_num'] : '', //
                'tourists_phone'   => $v['tourists_phone'] ? $v['tourists_phone'] : '', //
                'tourists_type'    => $v['tourists_type'] ? $v['tourists_type'] : 1,
                'order_id'         => $this->order_id,
                'tourists_remarks' => $v['tourists_remarks'] ? $v['tourists_remarks'] : '',
                'is_contact'       => $contenct_index == $k ? 1 : 0,
                'create_time'      => time(),
                'reseller_id'      => $this->reseller_id,
                'tourists_address' => $v['tourists_address'],
            ];
        }
        $res = $m_t->addAll($insert_t);
        if ($res === false) {
            M()->rollback();
            die(json_encode(['status' => 10.1, 'msg' => '游客信息写入失败']));
        }
        if (!empty($insert_v)) {
            $res1 = $m_v->addAll($insert_v);
            if ($res1 === false) {
                M()->rollback();
                die(json_encode(['status' => 10, 'msg' => '游客信息写入失败']));
            }
        }

    }

    //递归删除数组空值
    public function arrayRemoveEmpty($arr)
    {
        $narr = array();
        while (list($key, $val) = each($arr)) {
            if (is_array($val)) {
                $val = $this->arrayRemoveEmpty($val);
                if (count($val) != 0) {
                    $narr[$key] = $val;
                }

            } else {
                if (trim($val) != "") {
                    $narr[$key] = $val;
                }

            }
        }
        unset($arr);
        return $narr;
    }

    /**
     * 返回时间 2017-09-12格式
     * @param int $num 第几天
     * @return string
     */
    public function dateTime($num)
    {
        return date('Y-m-d', strtotime($this->day) + 86400 * ($num - 1));
    }
}
